import React, { useState, useEffect, useCallback } from 'react';
import { Button, Table, Modal, Form, Input, notification, Row, Col } from 'antd';
import { fetchApi } from '../../general/api';
import SelectProject from '../project/project_select';
import SelectDynamicType from "../../general/type_select";

interface AlarmConfigGroup {
    alarm_config_group_id: number;
    alarm_config_group_name: string;
    project_id: string;
    alarm_config_group_url: string;
    alarm_config_group_token: string;
    alarm_config_group_token_type: string;
    alarm_config_group_cron_schedule: string;
    alarm_config_group_code: string;
    alarm_config_group_instruction: string;
}

const ManageAlarmConfigGroup: React.FC = () => {
    const [controllerList, setControllerList] = useState<AlarmConfigGroup[]>([]); // 项目列表
    const [selectedRows, setSelectedRows] = useState<AlarmConfigGroup[]>([]); // 选中行
    const [alarmConfigGroupId, setAlarmConfigGroupId] = useState<number>(0); // 设为 0 或其他合适的初始值
    const [isEditMode, setIsEditMode] = useState(false); // 编辑模式状态
    const [isModalOpen, setIsModalOpen] = useState(false); // 弹框显示状态
    const [form] = Form.useForm(); // 表单实例
    const [selectedProject, setselectedProject] = useState<string | undefined>(undefined);

    // 表格列定义
    const getTableColumns = () => [
        { title: '连接器名称', dataIndex: 'alarm_config_group_name', width: 150 },
        { title: '地址', dataIndex: 'alarm_config_group_url', width: 150 },
        { title: '连接周期', dataIndex: 'alarm_config_group_cron_schedule', width: 150 },
        { title: 'token类型', dataIndex: 'alarm_config_group_token_type', width: 150 },
        { title: '连接类型', dataIndex: 'alarm_config_group_code', width: 150 },
        { title: '备注', dataIndex: 'alarm_config_group_instruction', width: 150 },
    ].map((col) => ({
        ...col,
        ellipsis: true,
        render: (text: string | React.ReactNode) => (
            <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'block' }}>
                {text}
            </span>
        ),
    }));

    // 获取项目列表数据
    const fetchControllerList = useCallback(async () => {
        try {
            const response_data = await fetchApi('/easymonitor/api/controllers', {
                method: 'GET',
            });
            setControllerList(response_data);
            setSelectedRows([]);
        } catch (error) {
            notification.error({
                message: '请求失败',
                description: `获取项目列表失败: ${error}`,
                duration: 2,
            });
        }
    }, []);

    // 显示通知
    const showNotification = (type: 'success' | 'error' | 'warning', message: string, description: string) => {
        notification[type]({ message, description, duration: 2 });
    };

    // 处理项目选择  
    const handleProjectChange = (value: string, label: string) => {
        setselectedProject(value); // Set the selected project value  
        form.setFieldsValue({ project_id: value }); // Update the form's project_id field  
    };

    // 打开新增/编辑弹框
    const openModal = (record: AlarmConfigGroup | null = null) => {
        setIsModalOpen(true);
        setIsEditMode(!!record);
        if (record) {
            setAlarmConfigGroupId(record.alarm_config_group_id); // 设置告警组ID
            setselectedProject(record.project_id);
            form.setFieldsValue(record);
        } else {
            setAlarmConfigGroupId(0); // 清空告警组ID
            form.resetFields();
        }
    };

    // 关闭弹框
    const closeModal = () => {
        setIsModalOpen(false);
        form.resetFields();
    };

    // 提交表单
    const handleSubmit = async (values: AlarmConfigGroup) => {
        try {
            const method = isEditMode ? 'PUT' : 'POST';
            const endpoint = '/easymonitor/api/controllers'; // 修改为实际接口

            // 如果是编辑模式，确保 alarm_config_group_id 存在
            if (isEditMode) {
                values.alarm_config_group_id = alarmConfigGroupId;
            }

            await fetchApi(endpoint, {
                method,
                body: JSON.stringify(values),
            });

            notification.success({
                message: isEditMode ? '编辑成功' : '新增成功',
                duration: 2,
            });
            closeModal();
            fetchControllerList();
        } catch (error: unknown) {
            if (error instanceof Error) {
                notification.error({
                    message: '操作失败',
                    description: error.message,
                    duration: 2,
                });
            } else {
                notification.error({
                    message: '操作失败',
                    description: '发生了未知错误',
                    duration: 2,
                });
            }
        }
    };

    // 删除选中的项目
    const handleDelete = async () => {
        if (selectedRows.length === 0) {
            showNotification('warning', '警告', '请选择至少一条记录进行删除！');
            return;
        }

        Modal.confirm({
            title: '确认删除',
            content: `确定要删除选中的 ${selectedRows.length} 个项目吗？`,
            onOk: async () => {
                try {
                    await fetchApi('/easymonitor/api/controllers', {
                        method: 'DELETE',
                        body: JSON.stringify(selectedRows),
                    });

                    showNotification('success', '删除成功', '选中的项目已成功删除。');
                    fetchControllerList();
                    setSelectedRows([]);
                } catch (error) {
                    showNotification('error', '删除失败', `删除操作失败: ${error}`);
                }
            },
        });
    };

    // 初始化加载数据
    useEffect(() => {
        fetchControllerList();
    }, [fetchControllerList]);

    return (
        <div style={{ display: 'flex', flexDirection: 'column', minHeight: '700px' }}>
            {/* 按钮区 */}
            <div style={{ marginBottom: '16px', display: 'flex', gap: '8px' }}>
                <Button type="primary" onClick={() => openModal()}>新增</Button>
                <Button
                    onClick={() => {
                        if (selectedRows.length !== 1) {
                            showNotification('warning', '警告', '请选择一条记录进行编辑！');
                        } else {
                            openModal(selectedRows[0]);
                        }
                    }}
                >
                    编辑
                </Button>
                <Button danger onClick={handleDelete}>删除</Button>
            </div>

            {/* 表格区 */}
            <Table
                size="small"
                columns={getTableColumns()}
                dataSource={controllerList}
                rowKey="alarm_config_group_id"
                pagination={{ position: ['bottomCenter'], pageSize: 12 }}
                rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: selectedRows.map((row) => row.alarm_config_group_id),
                    onChange: (_, rows) => setSelectedRows(rows),
                }}
                onRow={(record) => ({
                    onClick: () => {
                        const isSelected = selectedRows.some((row) => row.alarm_config_group_id === record.alarm_config_group_id);
                        const updatedRows = isSelected
                            ? selectedRows.filter((row) => row.alarm_config_group_id !== record.alarm_config_group_id)
                            : [...selectedRows, record];
                        setSelectedRows(updatedRows);
                    },
                })}
                style={{ overflowX: 'auto' }}
                locale={{ emptyText: '暂无数据' }}
            />

            {/* 新增/编辑弹框 */}
            <Modal
                title={isEditMode ? '编辑告警组' : '新增告警组'}
                open={isModalOpen}
                onOk={() => form.submit()}
                onCancel={closeModal}
                width="40%"  // Modal宽度
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                >
                    <Form.Item
                        label="告警组ID"
                        name="alarm_config_group_id"
                        style={{ display: 'none' }}  // 隐藏该字段
                    >
                        <Input type="hidden" value={alarmConfigGroupId} />
                    </Form.Item>
                    {/* 项目名和项目ID并排 */}
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                label="告警组名称"
                                name="alarm_config_group_name"
                                rules={[{ required: true, message: '请输入告警组名称！' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="项目ID"
                                name="project_id"
                                rules={[{ required: true, message: '请绑定一个项目' }]}
                            >
                                <SelectProject
                                    style={{ width: '100%' }}
                                    selectedCity={selectedProject}
                                    onCityChange={handleProjectChange} // Using the handleProjectChange function  
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    {/* 告警组URL和连接类型并排 */}
                    <Row gutter={16}>
                        <Col span={16}>
                            <Form.Item
                                label="告警组URL"
                                name="alarm_config_group_url"
                                rules={[{ required: true, message: '请输入告警组URL！' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="连接类型"
                                name="alarm_config_group_code"
                                rules={[{ required: true, message: '请选择一个连接类型！' }]}
                            >
                                <SelectDynamicType
                                    codeType="fetch_value_type"
                                    style={{ width: '100%' }}  // 使下拉框宽度自适应
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    {/* 告警组Token和Token类型并排 */}
                    <Row gutter={16}>
                        <Col span={16}>
                            <Form.Item
                                label="Cron表达式"
                                name="alarm_config_group_cron_schedule"
                                rules={[{ required: true, message: '请输入Cron表达式！' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                label="Token类型"
                                name="alarm_config_group_token_type"
                                rules={[{ message: '请选择一个Token类型！' }]}
                            >
                                <SelectDynamicType
                                    codeType="api_token_type"
                                    style={{ width: '100%' }}  // 使下拉框宽度自适应
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    {/* Cron表达式 */}
                    <Form.Item
                        label="告警组Token"
                        name="alarm_config_group_token"
                        rules={[{ message: '请输入告警组Token！' }]}
                    >
                        <Input.TextArea />
                    </Form.Item>

                    {/* 告警组说明 */}
                    <Form.Item
                        label="告警组说明"
                        name="alarm_config_group_instruction"
                    >
                        <Input.TextArea />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default ManageAlarmConfigGroup;
